<template>
  <div class="permission-setting">
    <div :class="isOpenSide ? 'side-left side-close' : 'side-left'" @mouseenter="mouseenter" @mouseleave="mouseleave"
      v-if="props.type != 'user'">
      <base-tree class="baseTree" :checkable="false" :treeData="treeData" :fieldNames="fieldNames"
        :selectedKeys="selectedOrgKeys" @selected_Keys="selected_Keys_left" :defaultExpandAll="defaultExpandAll"
        :expandedKeys="expanded_Keys"></base-tree>
      <div :class="isOpenSide ? 'open-right open-right-side' : 'open-right'" v-show="isShowIcon" @click="openorhideSide">
        <i v-if="isOpenSide" class="iconfont icon-a-doubleright" style="font-size: 20px">
        </i>
        <i v-else class="iconfont icon-a-doubleleft" style="font-size: 20px"> </i>
      </div>
    </div>
    <!-- 组织权限模板的tab切换 -->
    <div :class="query.userId ? 'side-right-user' : 'side-right'">
      <keep-alive>
        <permission-list :orgName="orgName" :selectedOrgKeys="selectedOrgKeys[0]" ref="psList" v-if="selectedOrgKeys"
          @assignable="isAssignable"></permission-list>
      </keep-alive>
    </div>
  </div>
  <div class="saveBtn" :style="styleWidth">
    <a-button type="primary" @click="saveSetting" :disabled="assignable ||  saveAble" style="margin-right: 8px">
      保存
    </a-button>
    <div class="reset">
      <a-popconfirm placement="topRight" @confirm="confirmReSet" v-if="!assignable">
        <template #title>
          <p style="width: 197px">
          您确定要重置权限吗?
          </p>
        </template>
        <a-button :disabled="assignable"> 重置 </a-button>
      </a-popconfirm>
      <a-button :disabled="assignable" v-else> 重置 </a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import baseTree from "@/components/tree/baseTree.vue";
import permissionList from "./permissionList/permissionList.vue";
import { systemStore } from "@/store/modules/systemStore";
import request from "@/api/index";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import {routerPerm} from '@/utils/common';
// type
interface dataSourceType {
  [propName: string]: any;
}
//props
const props = defineProps({
  type: {
    type: String,
    default: "",
  },
});
//data
const saveAble = ref<boolean>(false);
const { query } = useRoute();
// 路由传来的userId
const querUserId = ref<string | number | any>("");
const fieldNames = reactive({ title: "name", key: "id", disableCheckbox: "assignable" });

const isOpenSide = ref<boolean>(false);
const isShowIcon = ref<boolean>(false);
const sysStore = systemStore();
//树形结构数据
const defaultExpandAll = ref<Boolean>(false);
const expanded_Keys = ref<any>(undefined);
const treeData = ref<dataSourceType[]>([]);
const selectedOrgKeys = ref<(string | number | any)[]>([]);
const showName = ref<any>("")
//tabs
const psList = ref();
const orgName = ref<any>(null) // 选中组织name
// 保存按钮是否可点击
const assignable = ref<Boolean>(true);

//method
// 获取组织
const getRdecord = async (datas: dataSourceType = {}) => {
  // 获取左边tree数据
  const postData: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
  };
  const data = (await request.fetchUserOrgCurvirorg(postData)) || {};
  let reqData = data;
  treeData.value = reqData;
  nextTick(() => {
    defaultExpandAll.value = treeData.value.length ? true : false;
  });
};
// 选择组织
const selected_Keys_left = (obj: dataSourceType) => {
  selectedOrgKeys.value = obj.selected_Keys;
  orgName.value = findNameById(obj.selected_Keys, treeData.value);
};

// 根据id找name
const findNameById = function (id: any, data: any): any {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id == id) {
      return data[i].name;
    } else if (data[i].children) {
      const name = findNameById(id, data[i].children);
      if (name) {
        return name;
      }
    }
  }
}

//保存修改设置
const saveSetting = async () => {
  let tabActive = psList.value.tabActive;
  let siteTree = psList.value.siteTree; // 站群数据
  let checkSiteKeys = psList.value.checkSiteKeys; //站群选中的keys
  let menusTree = []; // 菜单数据
  let checkMenuKeys = []; // 菜单选中的keys
  let sitePerms = []; // 站点权限
  let updateDtoList: dataSourceType[] = [];
  if (tabActive == 1) {
    loop(siteTree, checkSiteKeys, updateDtoList);
  } else if (tabActive == 2) {
    menusTree = psList.value.menusTree; // 菜单数据
    checkMenuKeys = psList.value.checkMenuKeys; // 菜单选中的keys
    loop(menusTree, checkMenuKeys, updateDtoList);
  } else if (tabActive > 2) {
    sitePerms = psList.value.siteTable.dataSource;
    loopPerssionTree(sitePerms, updateDtoList);
  }
  let params: dataSourceType = {
    dataType: +tabActive,
    orgId: selectedOrgKeys.value[0],
    updateList: updateDtoList || [],
    siteId:
      tabActive == 4
        ? psList.value.sectionValue
        : tabActive == 5
          ? psList.value.documentValue
          : undefined,
    userId: querUserId.value || undefined,
    allPermissions:
      query.allPermissions === undefined
        ? undefined
        : query.allPermissions == "1"
          ? true
          : false,
  };
  if (tabActive <= 2) {
    saveSiteTreeOrmenusTree(params);
  } else {
    saveSiteChannelDocTree(params);
  }
};
//重置修改设置
const confirmReSet = async () => {
  let tabActive = psList.value.tabActive;
  let params: dataSourceType = {
    dataType: +tabActive,
    orgId: selectedOrgKeys.value[0],
    siteId:
      tabActive == 4
        ? psList.value.sectionValue
        : tabActive == 5
          ? psList.value.documentValue
          : undefined,
    userId: querUserId.value || undefined,
  };
  //
  request
    .resetSiteChannelDocumentPerm(params)
    .then((res: dataSourceType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        // 保存完成后刷新页面
        psList.value.getTreeData();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 保存站群权限和菜单权限
const saveSiteTreeOrmenusTree = (params: dataSourceType) => {
  request
    .fetchStationGroupMenuUpdate(params)
    .then((res: dataSourceType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        // 保存完成后刷新页面
        psList.value.getTreeData();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 保存站点权限、栏目权限、文档权限
const saveSiteChannelDocTree = (params: dataSourceType) => {
  request
    .fetchUpdateSiteChannelDocumentPerm(params)
    .then((res: dataSourceType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        // 保存完成后刷新页面
        psList.value.getTreeData();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 保存按钮更改状态
const isAssignable = (val: Boolean) => {
  assignable.value = !val;
};
// loop 扁平化站群、菜单数据
const loop = (data: dataSourceType[], keys: any[], list: dataSourceType[]) => {
  data.forEach((item: dataSourceType) => {
    item.selected = keys.length && keys.includes(item.id) ? true : false;
    list.push({ id: item.id, selected: item.selected });
    item.children && item.children.length ? loop(item.children, keys, list) : "";
  });
};
// loop 扁平化 站点、栏目、文档权限
const loopPerssionTree = (data: dataSourceType[], list: dataSourceType[]) => {
  console.log(JSON.parse(JSON.stringify(list)), 888);
  data.forEach((item: dataSourceType) => {
    let obj = {
      id: item.id,
      linePerms: [] as dataSourceType[],
    };
    item.linePerms.forEach((data: dataSourceType, index: number) => {
      obj.linePerms.push({
        operationId: +index + 1,
        selected: data.hasPerm,
      });
    });
    list.push(obj);

    item.children && item.children.length
      ? loopPerssionTree(item.children, JSON.parse(JSON.stringify(list)))
      : "";
  });
};
//展开收起侧边栏
const openorhideSide = () => {
  isOpenSide.value = !isOpenSide.value;
};

//侧边栏鼠标移入事件
const mouseenter = () => {
  isShowIcon.value = true;
};

//侧边栏鼠标移出事件
const mouseleave = () => {
  isShowIcon.value = isOpenSide.value ? true : false;
};

//onmounted
onMounted(() => {
    routerPerm().includes('saveAble') ? saveAble.value = false : saveAble.value = true;
  if (query.orgId) {
    selectedOrgKeys.value = [];
    selectedOrgKeys.value.push(+query.orgId);
  }
  if (query.userId) {
    querUserId.value = +query.userId;
  }
  if (props.type != "user") {
    getRdecord();
  }
  useFixeWidth();
});
</script>

<style lang="less" scoped>
.permission-setting {
  display: flex;
  flex-direction: row;
  padding: 24px;
  background: #ffffff;
  height: calc(100% - 120px);

  .side-left {
    width: 232px;
    max-height: 100%;
    border-right: 1px solid rgba(0, 0, 0, 0.06);
    padding-right: 4px;
    position: relative;
    transition: width 0.3s;
    padding-right: 24px;
    overflow: auto;

    .open-right {
      position: absolute;
      top: 50%;
      right: -1px;
      margin-top: -15px;
      bottom: -20px;
      height: 30px;
      width: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      background: #ffffff;
      border: 1px solid rgba(0, 0, 0, 0.06);
      z-index: 2;
    }

    .open-right-side {
      right: -20px;
    }

    .iconfont:hover {
      color: rgba(0, 0, 0, 0.6);
    }

    .iconfont {
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .side-right {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;
    padding-left: 24px;

    .reset {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  .side-right-user {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;
    // padding-left: 24px;

    .reset {
      position: absolute;
      top: 0;
      right: 0;
    }
  }

  .side-close {
    width: 0;
    padding-right: 0;
    transition: width 0.3s;
    overflow: visible;
  }
}

.saveBtn {
  position: fixed;
  bottom: 0;
  height: 48px;
  background-color: #fff;
  box-shadow: 0px -12px 48px 16px rgba(0, 0, 0, 0.03), 0px -9px 28px 0px rgba(0, 0, 0, 0.05), 0px -6px 16px -8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

::v-deep(.ant-tabs-tab) {
  padding: 0 0 10px 0;
}

::v-deep(::-webkit-scrollbar) {
  height: 10px;
}

::v-deep(.side-left .ant-tree-list-holder) {
  width: auto;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-close .ant-tree-list-holder) {
  width: 0;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-left .ant-tree-list:hover .ant-tree-list-scrollbar) {
  display: block !important;
}

::v-deep(.ant-tree-list .ant-tree-list-scrollbar) {
  display: none !important;
}

::v-deep(.ant-tree-list-scrollbar-thumb) {
  background: rgba(0, 0, 0, 0.15) !important;
}

::v-deep(.ant-checkbox + span) {
  padding-left: 12px;
  padding-right: 0;
}

::v-deep(.vxe-header--row .ant-checkbox + span) {
  font-weight: 500;
}

::v-deep(.ant-table-wrapper) {
  margin-top: 24px;
}

::v-deep(.ant-table-thead > tr > th) {
  padding: 16px 0 16px 16px;
}
::v-deep(.add-site-tip-top) {
  div {
    width: 100%;
  }
}
</style>
<style>
.section-tab .ant-table-wrapper {
  margin-top: 24px;
}

-wrapper {
  margin-top: 24px;
}

.document-tab .ant-table-wrapper {
  margin-top: 24px;
}

.ant-tooltip {
  max-width: 700px;
}
</style>
<style lang="less">
.side-left {
  .ant-tree {
    height: 100%;
    overflow: auto;

    .ant-tree-treenode {
      width: 100%;

      .ant-tree-node-content-wrapper {
        width: 100%;
      }
    }

    .ant-tree::-webkit-scrollbar {
      display: none;
    }

    .ant-tree:hover::-webkit-scrollbar {
      display: block;
    }

    .ant-tree-list-scrollbar-thumb {
      height: auto !important;
    }

    .ant-tree-list-holder {
      overflow-y: unset !important;
    }
  }
}
</style>
